const config = think.config('wxapp')
module.exports = class extends think.Service {
  /**
   * 获取微信小程序accessToken
   */
  async getWxAppAccessToken (appid = config.appId, secret = config.appSecret) {
    const cacheKey = `accessToken_${appid}`
    let d = await think.cache(cacheKey)
    if (!d) {
      const url = 'https://api.weixin.qq.com/cgi-bin/token'
      const map = {
        grant_type: 'client_credential',
        appid,
        secret
      }
      d = await yy.http.get(url, map)
      await think.cache(cacheKey, d, {
        type: 'file',
        file: {
          timeout: (d.expires_in - 200) * 1000
        }
      })
      yy.log.warn(d)
    }
    return d.access_token
  }
}
